package com.gzu.finalwork.common.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户上下文工具类
 * 用于获取当前操作人信息
 */
public class UserContextUtil {

    private static final Logger logger = LoggerFactory.getLogger(UserContextUtil.class);

    /**
     * 从请求中获取操作人信息
     * @param request HTTP请求对象
     * @return 操作人信息
     */
    public static Map<String, Object> getOperatorInfo(HttpServletRequest request) {
        Map<String, Object> operatorInfo = new HashMap<>();
        
        try {
            // 尝试从多个来源获取用户信息
            
            // 1. 从Session中获取用户信息
            Map<String, Object> sessionInfo = getFromSession(request);
            if (sessionInfo != null && !sessionInfo.isEmpty()) {
                operatorInfo.putAll(sessionInfo);
            }
            
            // 2. 从请求头中获取用户信息（JWT Token等）
            Map<String, Object> headerInfo = getFromHeaders(request);
            if (headerInfo != null && !headerInfo.isEmpty()) {
                operatorInfo.putAll(headerInfo);
            }
            
            // 3. 从请求参数中获取用户信息
            Map<String, Object> paramInfo = getFromParameters(request);
            if (paramInfo != null && !paramInfo.isEmpty()) {
                operatorInfo.putAll(paramInfo);
            }
            
            // 4. 如果都没有获取到，设置默认值
            if (operatorInfo.isEmpty()) {
                operatorInfo.put("operatorId", null);
                operatorInfo.put("operatorUsername", "anonymous");
                operatorInfo.put("operatorName", "匿名用户");
            }
            
        } catch (Exception e) {
            logger.warn("获取操作人信息失败: {}", e.getMessage());
            // 设置默认值
            operatorInfo.put("operatorId", null);
            operatorInfo.put("operatorUsername", "unknown");
            operatorInfo.put("operatorName", "未知用户");
        }
        
        return operatorInfo;
    }

    /**
     * 从Session中获取用户信息
     */
    private static Map<String, Object> getFromSession(HttpServletRequest request) {
        Map<String, Object> userInfo = new HashMap<>();
        
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                // 尝试获取常见的session key
                Object userId = session.getAttribute("userId");
                Object username = session.getAttribute("username");
                Object name = session.getAttribute("name");
                Object userObj = session.getAttribute("user");
                Object adminId = session.getAttribute("adminId");
                Object adminUsername = session.getAttribute("adminUsername");
                Object adminName = session.getAttribute("adminName");
                
                // 优先使用admin信息
                if (adminId != null) {
                    userInfo.put("operatorId", adminId);
                }
                if (adminUsername != null) {
                    userInfo.put("operatorUsername", adminUsername.toString());
                }
                if (adminName != null) {
                    userInfo.put("operatorName", adminName.toString());
                }
                
                // 如果没有admin信息，使用user信息
                else if (userId != null) {
                    userInfo.put("operatorId", userId);
                }
                if (username != null && !userInfo.containsKey("operatorUsername")) {
                    userInfo.put("operatorUsername", username.toString());
                }
                if (name != null && !userInfo.containsKey("operatorName")) {
                    userInfo.put("operatorName", name.toString());
                }
                
                // 如果有用户对象，尝试获取属性
                if (userObj != null && userInfo.isEmpty()) {
                    // 这里可以根据实际的用户对象结构来获取信息
                    // 例如：User user = (User) userObj;
                    // userInfo.put("operatorId", user.getId());
                    userInfo.put("operatorUsername", "session_user");
                    userInfo.put("operatorName", "会话用户");
                }
            }
        } catch (Exception e) {
            logger.debug("从Session获取用户信息失败: {}", e.getMessage());
        }
        
        return userInfo;
    }

    /**
     * 从请求头中获取用户信息
     */
    private static Map<String, Object> getFromHeaders(HttpServletRequest request) {
        Map<String, Object> userInfo = new HashMap<>();
        
        try {
            // 尝试从Authorization头获取JWT token
            String authorization = request.getHeader("Authorization");
            if (authorization != null && authorization.startsWith("Bearer ")) {
                // 这里可以解析JWT token获取用户信息
                // String token = authorization.substring(7);
                // 解析token的逻辑...
                userInfo.put("operatorUsername", "jwt_user");
                userInfo.put("operatorName", "JWT用户");
            }
            
            // 尝试从自定义头获取用户信息
            String userId = request.getHeader("X-User-Id");
            String username = request.getHeader("X-Username");
            String name = request.getHeader("X-User-Name");
            
            if (userId != null) {
                try {
                    userInfo.put("operatorId", Long.parseLong(userId));
                } catch (NumberFormatException e) {
                    userInfo.put("operatorId", null);
                }
            }
            if (username != null) {
                userInfo.put("operatorUsername", username);
            }
            if (name != null) {
                userInfo.put("operatorName", name);
            }
            
        } catch (Exception e) {
            logger.debug("从请求头获取用户信息失败: {}", e.getMessage());
        }
        
        return userInfo;
    }

    /**
     * 从请求参数中获取用户信息
     */
    private static Map<String, Object> getFromParameters(HttpServletRequest request) {
        Map<String, Object> userInfo = new HashMap<>();
        
        try {
            // 从请求参数中获取用户信息（不推荐，但作为备选方案）
            String userId = request.getParameter("operatorId");
            String username = request.getParameter("operatorUsername");
            String name = request.getParameter("operatorName");
            
            if (userId != null) {
                try {
                    userInfo.put("operatorId", Long.parseLong(userId));
                } catch (NumberFormatException e) {
                    userInfo.put("operatorId", null);
                }
            }
            if (username != null) {
                userInfo.put("operatorUsername", username);
            }
            if (name != null) {
                userInfo.put("operatorName", name);
            }
            
        } catch (Exception e) {
            logger.debug("从请求参数获取用户信息失败: {}", e.getMessage());
        }
        
        return userInfo;
    }
} 